package com.xp.framework;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author:xuecx
 * @descript:<p>编码器 </p>
 * @date:2019/4/29
 */
public class NettyEncoder extends MessageToByteEncoder<Object> {
    private Class<?> genericClass;
    private MySerializer serializer;

    public NettyEncoder(Class<?> genericClass, MySerializer serializer) {
        this.serializer = serializer;
        this.genericClass = genericClass;
    }

    /**
     * 编码
     */
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        if (genericClass.isInstance(o)) {
            byte[] data = serializer.serialize(o);
            byteBuf.writeInt(data.length);
            byteBuf.writeBytes(data);
        }
    }
}
